package lockTest;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class LockMain {

    public static void main(String[] args) {
        final LockUntil lockUntil = new LockUntil();

        new Thread(new Runnable() {
            @Override
            public void run() {
                lockUntil.write(Thread.currentThread());
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                lockUntil.get(Thread.currentThread());
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                lockUntil.get(Thread.currentThread());
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                lockUntil.get(Thread.currentThread());
            }
        }).start();
    }

    public static class LockUntil {
        private int x = 0;
        private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

        public void get(Thread thread) {
            this.lock.readLock().lock();
            try {
                System.out.println("start time:"+System.currentTimeMillis());
                for(int i=0; i<2; i++){
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(thread.getName() + ":" + this.x);
                }
                System.out.println(thread.getName() + ":读操作完毕！");
                System.out.println("end time:"+System.currentTimeMillis());
            }finally {
                this.lock.readLock().unlock();
            }
        }

        public void write(Thread thread) {
            this.lock.writeLock().lock();
            try {
                System.out.println("start time:"+System.currentTimeMillis());
                for(int i=0; i<5; i++){
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(thread.getName() + ":" + ++x);
                }
                System.out.println(thread.getName() + ":写操作完毕！");
                System.out.println("end time:"+System.currentTimeMillis());
            }finally {
                this.lock.writeLock().unlock();
            }
        }
    }
}

